//
//  ContactsViewController.m
//  BrushFace
//
//  Created by 小小旭 on 15/12/6.
//  Copyright © 2015年 Zzz. All rights reserved.
//

#import "ContactsViewController.h"
#import <AddressBookUI/AddressBookUI.h>
#import "ZCAddressBook.h"
#import "NavHelper.h"
#import "ContactViewModel.h"
#import "ContactModel.h"
#import "FriendListCell.h"

@interface ContactsViewController ()<UITableViewDelegate,UITableViewDataSource,ABPeoplePickerNavigationControllerDelegate>//ABPeoplePickerNavigationControllerDelegate
{
    NSMutableDictionary                 *contactInfoDic;
    NSMutableArray                      *indexArray;
    __weak IBOutlet UITableView         *contactTableView;
}

@property (nonatomic, strong)ContactViewModel *viewModel;

@end

@implementation ContactsViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    //获得Vcard
    NSDictionary *infoDic= [[ZCAddressBook shareControl]getPersonInfo];
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (NSString *key in infoDic) {
        NSArray *subArr = [infoDic objectForKey:key];
        [array addObjectsFromArray:subArr];
    }
    NSMutableArray *uploadArr = [NSMutableArray array];
    for (NSDictionary *subDict in array) {
        NSDictionary *uploadDict = @{@"fullname":subDict[@"name"],
                                     @"phone":subDict[@"telphone"]
                                     };
        [uploadArr addObject:uploadDict];
    }
    
    //上传通讯录
    [_viewModel connection_uploadAddressBookWithArray:uploadArr andCB:^(id output) {
        NSLog(@"%@",output);
    }];
    
    
    [self dataInit];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navBar setHideLeftBtn:YES];
    [self.navBar setTitle:@"通讯录"];
    contactTableView.backgroundColor = UIColorFromRGB(ColorValueForBackView_Gray);
    contactTableView.sectionIndexColor = [UIColor grayColor];
    contactTableView.sectionIndexBackgroundColor= [UIColor clearColor];
    contactTableView.tableFooterView = [[UIView alloc]init];
    
    indexArray = [[NSMutableArray alloc] init];
    _viewModel = [ContactViewModel SceneModel];
//    contactTableView.sectionIndexTrackingBackgroundColor=BB_White_Color;
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * header = [[UIView alloc] init];
    header.backgroundColor = UIColorFromRGB(ColorValueForBackView_Gray);
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, 100, 30)];
    label.text = indexArray[section];
    [header addSubview:label];
    return header;
}

#pragma mark - DataSource实现
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return indexArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[contactInfoDic objectForKey:[NSString stringWithFormat:@"%@",indexArray[section]]] count];
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        return nil;
    }
    
    return indexArray;
}
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    //点击索引，列表跳转到对应索引的行
    [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    return index;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellReuseID = @"cellReuseID";
    FriendListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseID];
    if (cell == nil) {
        cell = [FriendListCell loadBundleNib];
        cell.backgroundColor = [UIColor whiteColor];
    }
    NSString *headerStr = [NSString stringWithFormat:@"%@%@",HEADERIMAGE_FETCH,[contactInfoDic objectForKey:[NSString stringWithFormat:@"%@",indexArray[indexPath.section]]][indexPath.row][@"userId"]];
    [cell.localImage sd_setImageWithURL:[NSURL URLWithString:headerStr] placeholderImage:nil];
    cell.nameLabel.text = [self replayBaseStr:[contactInfoDic objectForKey:[NSString stringWithFormat:@"%@",indexArray[indexPath.section]]][indexPath.row][@"nickName"]];
    return cell;
}

#pragma mark - 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *friendId = [contactInfoDic objectForKey:[NSString stringWithFormat:@"%@",indexArray[indexPath.section]]][indexPath.row][@"userId"];
    NSLog(@"%@",friendId);
    [NavHelper gotoContactDetailVCWithUserId:friendId];
}

- (IBAction)addFriend:(id)sender {
    [NavHelper gotoAddFriendVC];
}

- (IBAction)finFriend:(id)sender {
    [NavHelper gotoErDuFriendVC];
}


#pragma mark customMethods  
- (void)dataInit{
   
    //获取我的好友
    [self.viewModel connection_getLevel1RelationAndCB:^(id output) {
        //NSLog(@"%@%@",indexArray,output);
        contactInfoDic = output;
        [indexArray removeAllObjects];
        for (NSString *key in output)
        {
           [indexArray addObject:key];
        }
        indexArray = [self paixu:indexArray];
        [contactTableView reloadData];
    }];
    
}
-(NSMutableArray *)paixu:(NSMutableArray *)array
{
    for (int i=0; i<array.count -1; i++)
    {
                 int m =i;
                for (int j =i+1; j<array.count; j++)
                {
 if ([[array objectAtIndex:j]compare:[array objectAtIndex:m] ]==-1)
                         {
                                m = j;
                         }
                     }
                if (m != i)
                {
                        [self swapWithData:array index1:m index2:i];
                }
            }
        return array;
}

-(void)swapWithData:(NSMutableArray *)aData index1:(NSInteger)index1 index2:(NSInteger)index2{
         NSNumber *tmp = [aData objectAtIndex:index1];
        [aData replaceObjectAtIndex:index1 withObject:[aData objectAtIndex:index2]];
        [aData replaceObjectAtIndex:index2 withObject:tmp];
     }

- (NSString *)replayBaseStr:(NSString *)nickName{
    NSMutableString *nickN = [[NSMutableString alloc]initWithString:nickName];
    NSMutableString *retStr = [[NSMutableString alloc] init];
    for (int i=0; i<nickN.length; i+=4) {
        NSString *subStr = [NSString stringWithFormat:@"\\u%@",[nickN substringWithRange:NSMakeRange(i, 4)]];
        [retStr appendString:[self replaceUnicode:subStr]];
    }
    return retStr;
}

- (NSString *)replaceUnicode:(NSString *)unicodeStr {
    NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
                                                           mutabilityOption:NSPropertyListImmutable
                                                                     format:NULL
                                                           errorDescription:NULL];
    
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"];
}

@end
